package petrochina.company.electric.ui.fragment;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.WrapRecyclerView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import okhttp3.Call;
import petrochina.company.electric.R;
import petrochina.company.electric.app.AppActivity;
import petrochina.company.electric.app.TitleBarFragment;
import petrochina.company.electric.event.ManagerHandleTaskResultEvent;
import petrochina.company.electric.event.TaskStatusChangeEvent;
import petrochina.company.electric.event.TaskStepStatusChangeEvent;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.api.PersonnelListApi;
import petrochina.company.electric.http.api.TaskListApi;
import petrochina.company.electric.http.api.TaskReceiveApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.model.TaskReceiveData;
import petrochina.company.electric.model.TaskResult;
import petrochina.company.electric.ui.activity.TaskDetailActivity;
import petrochina.company.electric.ui.adapter.TaskAdapter;
import petrochina.company.electric.ui.dialog.PersonnelListSelectDialog;

/**
 * desc   : 任务 Fragment
 */
public final class TaskFragment extends TitleBarFragment<AppActivity>
        implements OnRefreshLoadMoreListener,
        BaseAdapter.OnItemClickListener {


    public static TaskFragment newInstance() {
        return new TaskFragment();
    }

    private LoginApi.Bean loginData;
    private MMKV mmkv;
    private Gson gson;
    private SmartRefreshLayout mRefreshLayout;
    private WrapRecyclerView mRecyclerView;

    private TaskAdapter mAdapter;

    private AttachPopupView rightTitlePop;

    private int currentState = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.task_fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();
        mRefreshLayout = findViewById(R.id.rl_task_refresh);
        mRecyclerView = findViewById(R.id.rv_task_list);

//        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableAutoLoadMore(false);
    }

    @Override
    protected void initData() {
        String loginJson = mmkv.getString("loginData", null);
        if (!TextUtils.isEmpty(loginJson)) {
            try {
                loginData = gson.fromJson(loginJson, LoginApi.Bean.class);
            } catch (Exception e) {

            }
        }
        mAdapter = new TaskAdapter(getAttachActivity(), loginData);
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        getListData();
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public void onRightClick(View view) {
        rightTitlePop = new XPopup.Builder(getContext())
                .borderRadius(10)
                .hasShadowBg(false)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .offsetX(30)
                .isDarkTheme(true)
                .shadowBgColor(R.drawable.shape_bar_pop_bg)
                .atView(view)
                .asAttachList(new String[]{"全部", "今日已完成", "进行中", "未完成"},
                        new int[]{},
                        (position, text) -> {
                            switch (position) {
                                case 0:
                                    currentState = -1;
                                    break;
                                case 1:
                                    currentState = 2;
                                    break;
                                case 2:
                                    currentState = 1;
                                    break;
                                case 3:
                                    currentState = 0;
                                    break;
                            }
                            // 刷新
                            getListData();
                        });
        rightTitlePop.show();
    }

    public void getListData() {
        EasyHttp.get(this)
                .api(new TaskListApi().setState(currentState))
                .request(new HttpCallback<HttpData<List<TaskListApi.Bean>>>(this) {

                    @Override
                    public void onSucceed(HttpData<List<TaskListApi.Bean>> result) {
                        mAdapter.setData(result.getData());
                        mRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        mRefreshLayout.finishRefresh();
                    }
                });
    }


    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        TaskListApi.Bean bean = mAdapter.getItem(position);
        if (loginData == null) {
            return;
        }
        // 监管身份可查看所有任务
        if (loginData.getDutyType() == 1) {
            TaskDetailActivity.start(getAttachActivity(), bean);
        } else if (loginData.getDutyType() == 2) {
            if (bean.getStaffId() == 0) {
                EasyHttp.get(this)
                        .api(new PersonnelListApi())
                        .request(new HttpCallback<HttpData<List<PersonnelListApi.Bean>>>(this) {

                            @Override
                            public void onSucceed(HttpData<List<PersonnelListApi.Bean>> result) {
                                showPersonnelDialog(bean, result.getData());
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }

                        });
            } else {
                if (loginData.getId() == bean.getStaffId()) {
                    // id相同，本人进入任务详情
                    TaskDetailActivity.start(getAttachActivity(), bean);
                } else {
                    // 任务已被领取
                    ToastUtils.show("该任务已被领取");
                }
            }
        }
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            mAdapter.clearData();
            getListData();
//            mAdapter.setData(analogData());
        }, 1000);
    }

    /**
     * 任务操作人选择弹框
     *
     * @param item
     * @param list
     */
    private void showPersonnelDialog(TaskListApi.Bean item, List<PersonnelListApi.Bean> list) {
        // 蓝牙锁弹框
        PersonnelListSelectDialog.Builder mPersonnelDialogBuilder = new PersonnelListSelectDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                .setAutoDismiss(false)
                .setGravity(Gravity.BOTTOM)
                .setList(list)
                .setListener(new PersonnelListSelectDialog.OnListener<PersonnelListApi.Bean>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, PersonnelListApi.Bean person) {
                        dialog.dismiss();
                        submitTaskReceive(item, person);
                        TaskDetailActivity.start(getAttachActivity(), item);
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        dialog.dismiss();
                    }
                });
        mPersonnelDialogBuilder.show();
    }

    private void submitTaskReceive(TaskListApi.Bean item, PersonnelListApi.Bean person) {
        TaskReceiveData data = new TaskReceiveData(item.getId(), person.getId(), loginData.getId());
        String dataJson = gson.toJson(data);
        EasyHttp.post(this)
                .api(new TaskReceiveApi())
                .json(dataJson)
                .request(new HttpCallback<HttpData<TaskReceiveApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TaskReceiveApi.Bean> result) {
                        EventBus.getDefault().post(new TaskStepStatusChangeEvent(1));
                        ToastUtils.show("任务领取成功");
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            mAdapter.clearData();
            EasyHttp.get(this)
                    .api(new TaskListApi())
                    .request(new HttpCallback<HttpData<List<TaskListApi.Bean>>>(this) {

                        @Override
                        public void onSucceed(HttpData<List<TaskListApi.Bean>> result) {
                            mAdapter.setData(result.getData());
                            mRefreshLayout.finishLoadMore();
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                            mRefreshLayout.finishLoadMore();
                        }
                    });


            mAdapter.setLastPage(mAdapter.getCount() >= 100);
            mRefreshLayout.setNoMoreData(mAdapter.isLastPage());
        }, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskStepStatusChangeEvent event) {
        if (event != null) {
            if (event.getType() == 1) {
                getListData();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskStatusChangeEvent event) {
        if (event != null) {
            if (event.getType() == 1) {
                getListData();
            }
        }
    }
}